<template>
	<div>
		<div v-if="hasPermission('90630230')" class="show-add-btn">
			<el-button
				:disabled="isEdit"
				:type="isEdit ? 'info' : 'primary'"
				@click="handleAdd"
				size="small"
			>
				{{ $t('common.add') }}
			</el-button>
		</div>
		<el-table
			v-loading="loading"
			element-loading-spinner="el-icon-loading"
			border
			stripe
			size="mini"
			class="small-size-table"
			:data="dataList"
			style="width: 100%;"
			header-align="center"
			:header-cell-style="getRowClass"
		>
			<el-table-column
				type="index"
				label="序号"
				width="80"
				fixed="left"
				align="center"
			/>
			<el-table-column
				:label="anteRangeStartName"
				min-width="120"
				fixed="left"
				align="center"
			>
				<template slot-scope="scope">
					<template v-if="isLookHandConfigType">
						<el-input
							v-if="isSelectRow(scope.$index)"
							v-model="submitForm.potRangeStart"
							style="width: 90px;"
							:maxlength="7"
							:disabled="isFixedRow(scope.$index)"
							v-input="{ name: 'int' }"
						/>
						<span v-else>{{ scope.row.potRangeStart }}</span>
					</template>
					<template v-else>
						<el-input
							v-if="isSelectRow(scope.$index)"
							v-model="submitForm.anteRangeStart"
							style="width: 90px;"
							:maxlength="7"
							:disabled="isFixedRow(scope.$index)"
							v-input="{ name: 'int' }"
						/>
						<span v-else>{{ scope.row.anteRangeStart }}</span>
					</template>
				</template>
			</el-table-column>
			<el-table-column
				v-for="(item, index) in dataColumns"
				:key="index"
				:row-key="index"
				:label="item.label"
				:min-width="
					item.minWidth ||
						columnWidthArr[item.columnWidthType] ||
						columnWidthArr[item.valueAddedType] ||
						columnWidthArr['0']
				"
				align="center"
			>
				<template slot-scope="scope">
					<ConfigItemEdit
						v-if="isSelectRow(scope.$index)"
						:configType="scope.row.type"
						:configItem="
							getColumnConfigItem(
								item.valueAddedType,
								scope.row.configItem
							)
						"
						@updateConfigItem="updateConfigItem"
					/>
					<ConfigItemShow
						v-else
						:configType="scope.row.type"
						:configItem="
							getColumnConfigItem(
								item.valueAddedType,
								scope.row.configItem,
								item.code
							)
						"
					/>
				</template>
			</el-table-column>
			<el-table-column
				label="操作"
				min-width="140"
				fixed="right"
				align="center"
			>
				<template slot-scope="scope">
					<div class="show-action-btn">
						<template v-if="isSelectRow(scope.$index)">
							<el-button
								type="text"
								class="action-button"
								:disabled="submitLoading"
								@click="handleCancel"
							>
								{{ $t('common.cancel') }}
							</el-button>
							<el-button
								type="text"
								class="action-button"
								:loading="submitLoading"
								@click="handleSubmit(scope.row)"
							>
								{{ $t('common.save') }}
							</el-button>
						</template>
						<template v-else>
							<el-button
								v-if="hasPermission('90630231')"
								type="text"
								class="action-button"
								:disabled="isEdit"
								@click="handleEdit(scope)"
							>
								{{ $t('common.edit') }}
							</el-button>
							<el-button
								v-if="
									!isFixedRow(scope.$index) &&
										hasPermission('90630232')
								"
								type="text"
								class="action-button"
								:disabled="isEdit"
								:loading="
									scope.$index === currentIndex &&
										submitLoading
								"
								@click="
									handleDelete(scope.$index, scope.row.id)
								"
							>
								{{ $t('common.delete') }}
							</el-button>
						</template>
					</div>
				</template>
			</el-table-column>
		</el-table>
	</div>
</template>

<script>
import list from '@/mixins/list'
import {
	isActionDelayValueAddedTypeFunc,
	isInteractiveConfigTypeFunc,
	isLookHandConfigTypeFunc
} from '../configItemDict'
import ConfigItemEdit from '../ConfigItemEdit/index.vue'
import ConfigItemShow from '../ConfigItemShow/index.vue'
export default {
	components: { ConfigItemEdit, ConfigItemShow },
	mixins: [list],
	props: {
		configType: {
			type: Number,
			default: 0
		},
		anteRangeStartName: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			loading: false,
			submitLoading: false,
			isEdit: false,
			isAdd: false,
			isDelete: false,
			submitForm: { anteRangeStart: undefined, potRangeStart: undefined },
			currentIndex: undefined,
			dataList: [],
			dataListLen: 0,
			isLookHandConfigType: isLookHandConfigTypeFunc(this.configType)
		}
	},
	computed: {
		columnWidthArr() {
			if (this.isEdit) {
				return {
					0: '270',
					15: '730',
					16: '730',
					5960: '420'
				}
			} else {
				return {
					0: '180',
					15: '360',
					16: '360'
				}
			}
		}
	},
	watch: {
		configType: {
			handler() {
				this.isEdit = false
				this.loadConfigList()
			},
			immediate: true
		}
	},
	methods: {
		updateConfigItem(newConfigItem) {
			this.submitForm.configItem[
				this.submitForm.configItem.findIndex(
					(row) => row.valueAddedType === newConfigItem.valueAddedType
				)
			] = newConfigItem
		},
		loadConfigList() {
			this.loading = true
			this.dataColumns = []
			this.dataList = []
			const listApi = isLookHandConfigTypeFunc(this.configType)
				? 'getLookHandAddedFeeConfigListBend'
				: 'getValueAddedFeeConfigListBend'
			const columnWidthType = isInteractiveConfigTypeFunc(this.configType)
				? 5960
				: undefined
			this.$api[listApi]({ type: this.configType })
				.then((res) => {
					if (Array.isArray(res?.data)) {
						this.dataColumns = res.data[0].configItem.map(
							(item) => {
								return {
									valueAddedType: item.valueAddedType,
									label: item.valueAddedName,
									columnWidthType: columnWidthType
								}
							}
						)
						this.dataList = res.data
						this.dataListLen = this.dataList.length
					}
				})
				.catch(() => {})
				.finally(() => {
					this.loading = false
				})
		},
		getColumnConfigItem(valueAddedType, configItems) {
			if (!valueAddedType) return {}
			const item = configItems.find(
				(row) => row.valueAddedType === valueAddedType
			)
			if (isActionDelayValueAddedTypeFunc(valueAddedType)) {
				const newItem = JSON.parse(JSON.stringify(item))
				this.formatSubConfigItem(newItem)
				return newItem
			} else {
				return item
			}
		},
		formatSubConfigItem(item) {
			const {
				billingType = 1,
				amount = '',
				limitAmount = '',
				multipleIncrStep = '',
				isFirstFree = false
			} = item.subConfig || {}

			item.subIsFirstFree = isFirstFree
			item.subBillingType = billingType
			item.subAmount = amount
			item.subLimitAmount = limitAmount
			item.subMultipleIncrStep = multipleIncrStep
			item.subConfig = null
		},
		handleEdit(scope) {
			this.currentIndex = scope.$index
			this.isEdit = true
			this.submitForm = JSON.parse(JSON.stringify(scope.row))
			this.submitForm.configItem
				.filter((item) =>
					isActionDelayValueAddedTypeFunc(item.valueAddedType)
				)
				.forEach((item) => {
					this.formatSubConfigItem(item)
				})
		},
		handleAdd() {
			if (this.dataList.length === 0) {
				this.$message.closeAll()
				this.$message.warning('没有初始配置，不能新增')
				return
			}
			this.submitForm = JSON.parse(JSON.stringify(this.dataList[0]))
			this.submitForm.id = undefined
			let defaultBillingType = 2 // 默认盲注倍数收费
			if (isLookHandConfigTypeFunc(this.configType)) {
				this.submitForm.potRangeStart = ''
				defaultBillingType = 4 // 默认底池比例收费
			} else {
				this.submitForm.anteRangeStart = ''
			}
			this.submitForm.configItem.forEach((item) => {
				item.billingType = defaultBillingType
				item.amount = ''
				item.rebate = ''
				item.ext = null
				item.subConfig = null
				if (isActionDelayValueAddedTypeFunc(item.valueAddedType)) {
					item.subIsFirstFree = false
					item.subBillingType = 1
					item.subAmount = ''
					item.subLimitAmount = ''
					item.subMultipleIncrStep = ''
				}
			})
			this.dataList.push(this.submitForm)
			this.currentIndex = this.dataListLen
			this.isEdit = true
			this.isAdd = true
		},
		// 校验盲注配置
		handleCheckAnteRangeStart() {
			const rangeStartKey = isLookHandConfigTypeFunc(this.configType)
				? 'potRangeStart'
				: 'anteRangeStart'
			if (this.isEmptyOrNullOrUndefined(this.submitForm[rangeStartKey])) {
				this.$message.warning(`${this.anteRangeStartName}不能为空`)
				return true
			}
			if (
				this.dataList.findIndex(
					(item, index) =>
						this.submitForm[rangeStartKey] == item[rangeStartKey] &&
						this.currentIndex !== index
				) > -1
			) {
				this.$message.warning(`${this.anteRangeStartName}重复，请检查`)
				return true
			}
			return false
		},
		// 校验配置项
		handleCheckConfigItem() {
			let valueAddedType = 0
			let tips = '未配置，请检查'
			let isFlag = false
			for (let i = 0; i < this.submitForm.configItem.length; i++) {
				const item = this.submitForm.configItem[i]
				this.submitForm.configItem[i].subConfig = null
				valueAddedType = item.valueAddedType
				// 固定收费校验: amount
				if (item.billingType === 1) {
					if (this.isEmptyOrNullOrUndefined(item.amount)) {
						isFlag = true
						break
					}
					if (
						isLookHandConfigTypeFunc(this.configType) &&
						Number(item.amount) <= 0
					) {
						tips = '固定收费不能等于0'
						isFlag = true
						break
					}
				}
				// 盲注倍数收费校验: amount
				if (item.billingType === 2) {
					if (this.isEmptyOrNullOrUndefined(item.amount)) {
						isFlag = true
						break
					}
				}
				// 单次行动指数递增校验
				if (item.billingType === 3) {
					if (
						this.isEmptyOrNullOrUndefined(item.subLimitAmount) ||
						this.isEmptyOrNullOrUndefined(item.subAmount) ||
						this.isEmptyOrNullOrUndefined(item.subMultipleIncrStep)
					) {
						isFlag = true
						break
					}
					if (Number(item.subAmount) <= 0) {
						tips = '单次行动指数递增，起始值应大于0'
						isFlag = true
						break
					}
					if (Number(item.subMultipleIncrStep) <= 1) {
						tips = '单次行动指数递增，倍增长应大于1'
						isFlag = true
						break
					}
					if (Number(item.subLimitAmount) < Number(item.subAmount)) {
						tips = '上限值必须大于等于起始值'
						isFlag = true
						break
					}
				}
				// 底池比例收费校验: amount
				if (item.billingType === 4) {
					if (this.isEmptyOrNullOrUndefined(item.amount)) {
						isFlag = true
						break
					}
					if (Number(item.amount) <= 0) {
						tips = '底池比例收费不能等于0'
						isFlag = true
						break
					}
				}
				// 返利校验
				if (
					isLookHandConfigTypeFunc(this.configType) ||
					isInteractiveConfigTypeFunc(this.configType)
				) {
					if (this.isEmptyOrNullOrUndefined(item.rebate)) {
						isFlag = true
						break
					}
					if (Number(item.rebate) > 100) {
						tips = '返利不能大于100'
						isFlag = true
						break
					}
				}
				// 互动道具返利校验
				if (
					isInteractiveConfigTypeFunc(this.configType) &&
					Number(item.amount) === 0 &&
					Number(item.rebate) > 0
				) {
					if (item.billingType === 1) {
						tips = '固定收费设置为0时, 返利只能设置为0'
					} else if (item.billingType === 2) {
						tips = '盲注倍数收费设置为0时, 返利只能设置为0'
					}
					isFlag = true
					break
				}
			}
			if (isFlag) {
				this.$message.warning(
					this.dataColumns.find(
						(item) => valueAddedType === item.valueAddedType
					)?.label + tips
				)
				return true
			}
			return false
		},
		// 转换数据格式: subConfig{subLimitAmount,multipleIncrStep,amount}
		formatSubmitForm() {
			const newSubmitForm = JSON.parse(JSON.stringify(this.submitForm))
			newSubmitForm.configItem
				.filter((item) =>
					isActionDelayValueAddedTypeFunc(item.valueAddedType)
				)
				.forEach((item) => {
					if (item.billingType === 3) {
						item.subConfig = {
							isFirstFree: item.subIsFirstFree || false,
							billingType: item.subBillingType,
							amount: item.subAmount,
							limitAmount: item.subLimitAmount,
							multipleIncrStep: item.subMultipleIncrStep
						}
					} else {
						item.subConfig = null
					}
					delete item.subIsFirstFree
					delete item.subBillingType
					delete item.subAmount
					delete item.subLimitAmount
					delete item.subMultipleIncrStep
				})
			return newSubmitForm
		},
		handleSubmit() {
			this.$message.closeAll()
			if (
				this.handleCheckAnteRangeStart() ||
				this.handleCheckConfigItem()
			) {
				return
			}
			const params = {
				id: this.submitForm.id,
				type: this.submitForm.type,
				vals: JSON.stringify(this.formatSubmitForm())
			}
			this.submitLoading = true
			this.$api
				.updateValueAddedFeeConfigBend(params)
				.then((res) => {
					this.submitLoading = false
					if (res.code === 200) {
						this.$message.success(this.$t('common.save_success'))
						this.isAdd = false
						this.isEdit = false
						this.loadConfigList()
					}
				})
				.catch(() => {
					this.submitLoading = false
				})
		},
		handleDelete(index, id) {
			this.currentIndex = index
			this.isDelete = true
			this.handleConfirm()
				.then(() => {
					this.submitLoading = true
					this.$api
						.deleteValueAddedFeeConfigBend({ id })
						.then((res) => {
							this.submitLoading = false
							if (res.code === 200) {
								this.$message.success(
									this.$t('common.delete_success')
								)
								this.loadConfigList()
							}
						})
						.catch(() => {
							this.submitLoading = false
						})
				})
				.finally(() => {
					this.isDelete = false
				})
		},
		handleCancel() {
			this.handleConfirm().then(() => {
				this.currentIndex = 0
				this.submitForm = {}
				this.isEdit = false
				if (this.isAdd) {
					this.dataList.pop()
					this.isAdd = false
				}
			})
		},
		handleConfirm() {
			return this.$confirm(
				`${
					this.isDelete
						? '确定删除此条配置？'
						: this.isAdd
						? '是否取消本次新增操作？'
						: '是否取消本次编辑操作？'
				}`,
				this.$t('common.components.tip'),
				{
					confirmButtonText: this.$t('common.sure'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					return Promise.resolve()
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
					return Promise.reject()
				})
		},
		isEmptyOrNullOrUndefined(val) {
			return val === '' || val === null || val === undefined
		},
		isSelectRow(index) {
			return this.isEdit && this.currentIndex === index
		},
		isFixedRow(index) {
			return index === 0
		}
	}
}
</script>

<style lang="scss" scoped>
.rule-form {
	margin: 15px 30px;
	.status-lable {
		line-height: 1.2;
	}
}
.show-add-btn {
	width: 100%;
	margin-bottom: 10px;
}

.show-action-btn {
	.action-button {
		min-width: 30px !important;
	}
}
</style>
